package com.example.factory.api.facade.impl;

import com.example.factory.api.dto.DtoUser;
import com.example.factory.api.dto.PageResponse;
import com.example.factory.api.dto.Response;
import com.example.factory.api.dto.assembler.UserAssembler;
import com.example.factory.api.dto.form.DtoQueryUserListForm;
import com.example.factory.api.dto.form.DtoUserForm;
import com.example.factory.api.facade.UserFacade;
import com.example.factory.core.domain.UserEntity;
import com.example.factory.core.repository.UserRepository;
import com.example.factory.core.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lei Tao
 */
@Service
public class UserFacadeImpl implements UserFacade {
    private final UserRepository userRepository;
    private final UserAssembler userAssembler;
    private final UserService userService;

    public UserFacadeImpl(UserRepository userRepository, UserAssembler userAssembler, UserService userService) {
        this.userRepository = userRepository;
        this.userAssembler = userAssembler;
        this.userService = userService;
    }

    @Override
    public Response<List<DtoUser>> retrieveUsers(DtoQueryUserListForm dtoQueryUserListForm) {
        Page<UserEntity> users = userRepository.findUsers(dtoQueryUserListForm);
        List<DtoUser> dtoUsers = userAssembler.toDtoUsers(users);
        long totalElements = users.getTotalElements();
        int totalPages = users.getTotalPages();
        return PageResponse.success(totalElements, totalPages, dtoUsers);
    }

    @Override
    public Response<DtoUser> retrieveUser(String userGuid) {
        UserEntity userEntity = userRepository.findByGuidAndArchivedFalse(userGuid);
        DtoUser dtoUser = userAssembler.toDtoUser(userEntity);
        return Response.success(dtoUser);
    }

    @Override
    public Response<Void> deleteUser(String userGuid) {
        userService.deleteUser(userGuid);
        return Response.success();
    }

    @Override
    public Response<DtoUser> saveOrUpdate(DtoUserForm dtoUserForm) {
        UserEntity userEntity = userAssembler.toUser(dtoUserForm);
        userService.saveOrUpdate(userEntity);
        DtoUser dtoUser = userAssembler.toDtoUser(userEntity);
        return Response.success(dtoUser);
    }
}
